import { message, Button, Form, Flex, Select } from "antd";
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { ProColumns } from '@ant-design/pro-components';
import 'react-area-linkage/dist/index.css';
import {
  EditableProTable, ProForm, ProFormDateTimePicker, ProFormSelect, ProFormText, ProFormTextArea,
} from '@ant-design/pro-components';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
import { uploadProduct } from '../../api/axios8081.js';



//城市级联选择器数据
interface Option {
  value: string;
  label: string;
  children?: Option[];
}

const options: Option[] = [
  {
    value: 'zhejiang',
    label: '浙江',
    children: [
      {
        value: 'hangzhou',
        label: '杭州',
        children: [
          {
            value: 'xihu',
            label: '西湖',
          },
        ],
      },
    ],
  },
  {
    value: 'jiangsu',
    label: '江苏',
    children: [
      {
        value: 'nanjing',
        label: '南京',
        children: [
          {
            value: 'zhonghuamen',
            label: '中华门',
          },
        ],
      },
    ],
  },

  {
    value: 'henan',
    label: '河南',
    children: [
      {
        value: 'zhongzhou',
        label: '郑州',
        children: [
          {
            value: 'zhongyuanqu',
            label: '中原区',
          },
        ],
      },
    ],
  },];

const onChange: CascaderProps<Option>['onChange'] = (value) => {
  console.log(value);
};




const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

type DataSourceType = {
  id: React.Key;
  score?: number;
  money?: number;
  state?: string;
  created_at?: number;
  children?: DataSourceType[];
};
//列表数组的数据
const defaultData: DataSourceType[] = [
  {
    id: 123,
    score: 123,
    money: 534,
    state: 'open',
    created_at: 1590486176000,
  },
  {
    id: 232,
    score: 42,
    money: 234,
    state: 'closed',
    created_at: 1590481162000,
  },
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '会员价格类型',
    key: 'state',
    dataIndex: 'state',
    valueType: 'select',
    valueEnum: {
      all: { text: '现金购买', status: 'Default' },
      open: {
        text: '纯积分',
        status: 'Error',
      },
      closed: {
        text: '积分加钱',
        status: 'Success',
      },
    },
  },
  {
    title: '积分数量',
    dataIndex: 'score',
    width: '30%',
  },

  {
    title: '现金价格',
    dataIndex: 'money',
    width: '30%',
  },

  {
    title: '操作',
    valueType: 'option',
  },
];


const { Option } = Select;


const AddGood: React.FC = () => {
  const navigate = useNavigate();
  const [account, setAccount] = useState('');
  const [password, setPassword] = useState('');
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  // //保存草稿功能
  // const handleSubmit = async (event:any) => {
  //     event.preventDefault();
  //     try {
  //       const response = await scratchpad({data})
  //       message.success("保存成功")
  //     } catch (error) {
  //       console.error('保存失败', error);

  //     }
  //   };


  return (
    <div>
      <ProForm<{
        useMode?: string;
      }>
        layout={'vertical'}
        labelCol={{ span: 20 }}
        wrapperCol={{ span: 20 }}
        onFinish={async (values) => {
          console.log('values', values);
          await waitTime(1000);
          try {
            const response = await uploadProduct({ values });
            console.log(values);
            navigate('/list/manage')//提交之后跳转主页面并且显示提交成功
            message.success('提交成功');
          } catch (error) {
            console.error("添加商品失败", error);
            navigate('/list/manage')
          }

        }
        }

      // params={{}}
      // request={async () => {
      //   await waitTime(100);
      //   return {
      //     name: '',
      //     useMode: 'chapter',
      //   };
      // }}
      >


        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>基本信息</h1>
        <Flex>
          <ProFormText name="name" label="商品名称" placeholder="请输入名称" rules={[{ required: true }, { max: 20 }]} />

          <ProFormText colProps={{ md: 12, xl: 8 }} name="imgUrl" initialValue="imgUrl" label="商品头图" placeholder="图片url" />
        </Flex>
        <ProFormTextArea colProps={{ span: 24 }} name="describes" initialValue="describes" label="商品文字描述" placeholder="请输入详细文字描述,最大不超过100字"
          rules={[{ required: true }]}
          fieldProps={{
            maxLength: 100, // 设置最大长度为100
          }}
        />
        <Flex>
          <ProFormSelect colProps={{ xl: 8, md: 8 }} initialValue="type" label="商品类型" name="type" placeholder="请选择" rules={[{ required: true }]}
            valueEnum={{
              1: '食品',
              2: '服装',
              3: '美妆',
              4: '科技',
              5: '玩具',
              6: '家具',
            }}
          />

          <ProFormText colProps={{ md: 8, xl: 8 }} initialValue="details" name="details" label="商品详情" placeholder="商品详情" rules={[{ required: true }]} />
          <ProFormSelect colProps={{ xl: 8, md: 8 }} initialValue="className" label="商品分类" name="className" placeholder="请选择商品分类" rules={[{ required: true }]}
            valueEnum={{
              1: '肉类',
              2: '蔬菜',
              3: '水果',
              4: '手机',
              5: '电玩',
              6: '电器',
            }}
          />
          <ProFormText colProps={{ md: 8, xl: 8 }} initialValue="num" name="num" label="商品库存" placeholder="商品库存" rules={[{ required: true }]} />
        </Flex>

        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>服务条款</h1>
        <Flex>
          <ProFormText colProps={{ md: 12, xl: 8 }} initialValue="company" name="company" label="供应商信息" rules={[{ required: true }]} />
          <ProFormText colProps={{ md: 12, xl: 8 }} initialValue="phoneNumber" name="phoneNumber" label="供应商联系方式"
            rules={[{ required: true },
            { len: 11, message: "联系方式需要为11位数字" }]}
            fieldProps={{
              maxLength: 11,//让用户输入11位之后就不能输入了
            }} />
        </Flex>

        <ProFormTextArea
          colProps={{ span: 24 }}
          name="productServer"
          initialValue="productServer"
          label="服务保障"
          placeholder="请输入服务保障"
          rules={[{ required: true }, { max: 100 }]}

        />
        {/* 表格数据 */}

        <ProForm.Item

          name="priceList"
          initialValue={defaultData}
          trigger="onValuesChange"
        >
          <EditableProTable<DataSourceType>
            rowKey="id"
            toolBarRender={false}
            columns={columns}
            recordCreatorProps={{
              newRecordType: 'dataSource',
              position: 'bottom',
              record: () => ({
                id: Date.now(),
                addonBefore: 'ccccccc',
                decs: 'testdesc',
              }),
            }}
            editable={{
              type: 'multiple',
              editableKeys,
              onChange: setEditableRowKeys,
              actionRender: (row, _, dom) => {
                return [dom.delete];
              },
            }}
          />
        </ProForm.Item>

        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>快递</h1>
        <Form.Item label="不发货地区" initialValue="unsendAddress" name="unsendAddress" rules={[{ required: true }]}>
          <Cascader options={options} onChange={onChange} placeholder="选择城市" />
        </Form.Item>
        <br />
        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>兑换限制</h1>
        <ProFormText
          name="limits"
          initialValue="limits"
          label="兑换上限"
          tooltip="1000000000"
          placeholder="请输入"
        />
        <br />
        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>投放</h1>
        <Flex>
          <ProFormDateTimePicker
            name="onlineTime"
            initialValue="onlineTime"
            label="上线时间"
            rules={[{ required: true }]}
            fieldProps={{
              format: (value) => value.format('YYYY-MM-DD'),
            }}
          />
          <ProFormDateTimePicker
            name="downlineTime"
            initialValue="downlineTime"
            label="下线时间"
            rules={[{ required: true }]}
            fieldProps={{
              format: (value) => value.format('YYYY-MM-DD'),
            }}
          />
        </Flex>
        <Form.Item initialValue="sendAddress" label="投放城市" name="sendAddress" rules={[{ required: true }]}>
          <Cascader options={options} onChange={onChange} placeholder="选择城市" />
        </Form.Item>

        <h1 style={{ fontSize: '1', fontWeight: 'bold' }}>管理员</h1>

        <ProFormSelect.SearchSelect
          name="userQuery3"
          label=" 请选择你的代理人"
          fieldProps={{
            labelInValue: false,
            style: {
              minWidth: 140,
            },
          }}
          options={[
            { label: 'user', value: 'all' },
            { label: 'root', value: 'open' },
            { label: 'fanda', value: 'closed' },
            { label: 'xingtu', value: 'processing' },
          ]}
        />
        {/* <Button onClick={handleSubmit} >保存</Button>  */}
      </ProForm>
    </div >
  );

};


export default AddGood;
